package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.StoreIn;
import com.wh.wisdomsite.xbox.pojo.st.StoreInAndOut;
import com.wh.wisdomsite.xbox.pojo.st.StoreOutConfirmIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.Store;
import com.wh.wisdomsite.xbox.st.entity.Supplier;
import com.wh.wisdomsite.xbox.st.service.IStoreService;
import com.wh.wisdomsite.xbox.st.service.ISupplierService;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;


/***
 *库存Controller
 * @author 杨世强
 * @date 16:40 2018/8/2
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/store")
public class StoreController {

    private static final Log logger = LogFactory.getLog(StoreController.class);
    
    @Autowired
    private IStoreService iStoreService;

    @Autowired
    private ISupplierService iSupplierService;




    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_store_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/store/storeList";
    }


    /**
     * 获取库存信息集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_store_find")
    @RequestMapping(value = "/storeList.do")
    public void storeList(HttpServletResponse response, StoreIn in) {
        try {
            logger.info("加载库存信息列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Store> page = new Page<Store>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Store> ewStore = new EntityWrapper<Store>();
            ewStore.setEntity(new Store());
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewStore.like("pr.prName", in.getPrName());
            }
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewStore.like("co.coNumber", in.getCoNumber());
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if(!UserUtils.isSysAdmin()){
                ewStore = UserUtils.setEntityWrapper(ewStore, "co1", "off", "pr");
            }
            ewStore.groupBy("st.coId");
            Page<Map<String,Object>> storePage = iStoreService.getMapsPage(page,ewStore);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (storePage.getRecords().size() > 0) {
                for (Map<String,Object> store : storePage.getRecords()) {
                    JSONObject object = new JSONObject(store);
                    array.put(object);
                }
            }
            json.put("total", storePage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载库存信息列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载库存信息列表-->>Exception" + e.getMessage());
        }
    }


    /**
     * 跳转库存详情
     *
     * @param request
     * @param in
     */
    @RequiresPermissions("rules:st_store_view")
    @RequestMapping(value = "/storeDesc.do")
    public String storeDesc(HttpServletRequest request, StoreIn in) {
        String coId = in.getCoId();
        request.setAttribute("coId",coId);
        return "/st/store/storeDetailList";
    }

    /**
     * 库存详情
     * @param response
     * @param in
     */
    @RequestMapping(value = "/storeDetailList.do")
    public void storeDetailList(HttpServletResponse response, StoreIn in) {
        try {
            logger.info("加载库存详情列表-->>开始");
            String coId = in.getCoId();
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            int total = 0;
            if(StringUtils.isNotEmpty(coId)){
                //设置分页
                if (in.getPage() == 0) in.setPage(1);
                if (in.getRows() == 0) in.setRows(10);
                Page<Store> page = new Page<Store>();
                page.setCurrent(in.getPage());
                page.setSize(in.getRows());
                //查询当前用户所在公司是否存在材料供应商
                Integer companyId = UserUtils.getCurrentUser().getCompanyId();
                EntityWrapper<Supplier> ewSupplier = new EntityWrapper<Supplier>();
                ewSupplier.setEntity(new Supplier());
                ewSupplier.eq("companyId", companyId);
                List<Supplier> suppliers = iSupplierService.selectList(ewSupplier);
                //设置条件
                EntityWrapper<Store> ewStore = new EntityWrapper<Store>();
                ewStore.setEntity(new Store());
                ewStore.eq("st.coId", in.getCoId());
                if (StringUtils.isNotEmpty(in.getMaterialName())) {
                    ewStore.like("ma.materialName", in.getMaterialName());
                }
                if (StringUtils.isNotEmpty(in.getStandardType())) {
                    ewStore.like("ma.standardType", in.getStandardType());
                }
               /* //若用户不是超级管理员添加所属公司条件
                if(!UserUtils.isSysAdmin() && suppliers.size() > 0){
                    ewStore.eq("sup.companyId", companyId);
                }*/
                Page<Map<String,Object>> storeDetailPage = iStoreService.getMapsDetailPage(page,ewStore);
                if (storeDetailPage.getRecords().size() > 0) {
                    int origIndex = 1;
                    for (Map<String,Object> store : storeDetailPage.getRecords()) {
                        JSONObject object = new JSONObject(store);
                        object.put("origIndex",origIndex);
                        array.put(object);
                        origIndex ++;
                    }
                    total = storeDetailPage.getTotal();
                }
            }
            json.put("total", total);
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载库存详情列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载库存详情列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转出库页面
     *
     * @param request
     * @param in
     */
    @RequiresPermissions("rules:st_store_pullBtn")
    @RequestMapping(value = "/toPullStore.do")
    public String toPullStore(HttpServletRequest request, StoreIn in) {
        String coId = in.getCoId();
        request.setAttribute("coId",coId);
        return "/st/store/storeOutRecordAdd";
    }


    /**
     * 确认出库
     * @param response
     * @param storeOutRecordList
     */
    @RequiresPermissions("rules:st_store_confirmBtn")
    @RequestMapping(value = "/savePull.do",method = RequestMethod.POST)
    public void savePull(HttpServletResponse response, @RequestBody List<StoreOutConfirmIn> storeOutRecordList) {
        try{
            logger.info("出库保存-->>开始");
            String userId = UserUtils.getCurrentUser().getUsId();
            iStoreService.savePull(storeOutRecordList,userId);
            response.getWriter().write(JsonUtil_Org.returnTrue("出库成功！"));
            logger.info("出库保存-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("出库保存-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转出入库详情页面
     * @param request
     * @param stId
     */
    @RequiresPermissions("rules:st_store_inAndOutBtn")
    @RequestMapping(value = "/toStoreInAndOut.do")
    public String toStoreInAndOut(HttpServletRequest request, String stId) {
        request.setAttribute("stId",stId);
        return "/st/store/inAndOutList";
    }


    /**
     * 出入库列表
     * @param response
     * @param in
     */
    @RequestMapping(value = "/inAndOutList.do")
    public void inAndOutList(HttpServletResponse response, StoreInAndOut in) {
        try {
            logger.info("加载出入库信息列表-->>开始");
            if(StringUtils.isEmpty(in.getStId())){
                return;
            }
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Store> page = new Page<Store>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<Store> ewStore = new EntityWrapper<Store>();
            ewStore.setEntity(new Store());
            ewStore.eq("st.stId",in.getStId());
            if (StringUtils.isNotEmpty(in.getStoType())) {
                ewStore.eq("sto.sto_type", in.getStoType());
            }
            if (StringUtils.isNotEmpty(in.getStoPerson())) {
                ewStore.like("sto.sto_person", in.getStoPerson());
            }
            if (StringUtils.isNotEmpty(in.getStoreWay())) {
                ewStore.like("sto.sto_storeWay", in.getStoreWay());
            }
            if (StringUtils.isNotEmpty(in.getStoStartTime()) && StringUtils.isNotEmpty(in.getStoEndTime())) {
                ewStore.between("sto.sto_date", in.getStoStartTime(), in.getStoEndTime() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStoStartTime())) {
                ewStore.between("sto.sto_date", in.getStoStartTime(), in.getStoStartTime() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStoEndTime())) {
                ewStore.between("sto.sto_date", in.getStoEndTime(), in.getStoEndTime() + " " + "23:59:59");
            }
            Page<Map<String,Object>> storePage = iStoreService.getStoreInAndOut(page,ewStore);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (storePage.getRecords().size() > 0) {
                for (Map<String,Object> store : storePage.getRecords()) {
                    JSONObject object = new JSONObject(store);
                    array.put(object);
                }
            }
            json.put("total", storePage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载出入库信息列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载出入库信息列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转入库列表页面
     * @param request
     * @param coId
     */
    @RequiresPermissions("rules:st_store_putBtn")
    @RequestMapping(value = "/toPutStore.do")
    public String toPutStore(HttpServletRequest request, String coId) {
        request.setAttribute("coId",coId);
        return "/st/store/storeInRecordAdd";
    }

    /**
     * 确认入库
     * @param response
     * @param request
     */
    @RequiresPermissions("rules:st_store_confirmBtn")
    @RequestMapping(value = "/savePutByRkt.do",method = RequestMethod.POST)
    public void savePutByRkt(String coId,HttpServletResponse response,HttpServletRequest request) {
        try {
            logger.info("添加入库-->>开始");
            if(StringUtils.isNotEmpty(coId)){
                String userId = UserUtils.getCurrentUser().getUsId();
                iStoreService.savePutByRkt(coId,userId,request);
                response.getWriter().write(JsonUtil_Org.returnTrue("添加入库成功"));
            }else{
                response.getWriter().write(JsonUtil_Org.returnFalse("添加入库失败"));
            }
            logger.info("添加入库-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("添加入库-->>Exception" + e.getMessage());
        }
    }


}
